package com.lanou.utp.service.impl;

import com.lanou.utp.entity.ResponseData;
import com.lanou.utp.entity.Student;
import com.lanou.utp.entity.User;
import com.lanou.utp.mapper.StudentMapper;
import com.lanou.utp.mapper.UserMapper;
import com.lanou.utp.service.StudentService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Transactional
@Service("studentService")
public class StudentServiceImpl implements StudentService {

    @Resource
    private StudentMapper studentMapper;
    @Resource
    private UserMapper userMapper;

    @Override
    @Transactional
    public Map<String,Object> selectStuAll(Integer page) {
        Integer size = 10*(page-1);
        List<Student> data = new ArrayList<>();
        List<Student> students = studentMapper.selectStuAll(size);
        for (Student student : students) {
            Long id = student.getId();
            User user = userMapper.selectUserById(id);
            student.setUser(user);
            data.add(student);
        }
        Integer total = studentMapper.selectTotal();
        HashMap<String,Object> paging = new HashMap<>();
        paging.put("page",page);
        paging.put("size",10);
        paging.put("total",total);
        HashMap<String,Object> map = new HashMap<>();
        map.put("code",200);
        map.put("message","ok");
        map.put("data",data);
        map.put("paging",paging);
        return map;
    }

    @Override
    @Transactional
    public ResponseData updateStu(Student student) {
        User user = student.getUser();
        Long id = student.getId();
        user.setId(id);
        userMapper.updateStu(user);
        studentMapper.updateStu(student);

        return new ResponseData("ok");
    }


    @Override
    @Transactional
    public ResponseData addStudent(Student student) {
        User user = student.getUser();
        userMapper.addStudent(user);
        student.setId(user.getId());
        studentMapper.addStudent(student);
        return new ResponseData("ok");
    }

    @Override
    public ResponseData delStudent(Integer id) {
        studentMapper.delStudent(id);
        userMapper.delUser(id);
        return new ResponseData("ok");
    }

    @Override
    public ResponseData delStudents(List<Integer> id) {
        studentMapper.delStudents(id);
        userMapper.delUsers(id);
        return new ResponseData("ok");
    }

    @Override
    public List<Student> getStudentsByClazzId(Integer id) {
        return this.studentMapper.getStudentsByClazzId(id);
    }
}
